/**
 * 
 */
package org.estock.config.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.estock.common.model.task.Task;

/**
 * @author richard
 *
 */
public class TaskDefs {
	private static final Logger logger = LoggerFactory.getLogger(TaskDefs.class);
	
	private static final String FILENAME_TASKDEF = "taskdef.xml";
	
	private static List<Task> taskdefs;
	
	public static List<Task> getTaskdefs() {
		if (taskdefs == null) {
			loadTaskDefs();
		}
		// reset nextSDateTime everytime we call it.
		for (Task taskDef : taskdefs) {
			taskDef.setNextSDateTime(new Date());
		}
		return taskdefs;
	}

	private static void loadTaskDefs() {
		taskdefs = XMLUtil.readXML(getTaskDefInputSteam(), Task.class);
	}

	public static InputStream getTaskDefInputSteam() {
		File file = new File(FILENAME_TASKDEF);
		if (file.exists()) {
			logger.debug("Fetching the list from a local file {}", FILENAME_TASKDEF);
			try {
				return new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		return TaskDefs.class.getClassLoader().getResourceAsStream(FILENAME_TASKDEF);
	}
	
}
